package com.clz.appdesign.appdependence.net.download;

import com.clz.appdesign.appdependence.rx.RxBus2;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * @author chenliangzhi
 * @date 2018/3/28
 * @describe
 */

public class ProgressResponseBody extends ResponseBody {
    private ResponseBody responseBody;
    private BufferedSource bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody) {
        this.responseBody = responseBody;
    }

    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (null == bufferedSource) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    private Source source(Source source) {
        return new ForwardingSource(source) {
            long byteReaded = 0;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                final long byteRead = super.read(sink, byteCount);
                byteReaded += byteRead == -1 ? 0 : byteRead;
                //实时发送当前总字节和已读取的字节
                RxBus2.getInstance().post(new FileLoadEvent(contentLength(), byteReaded));
                return byteRead;
            }
        };
    }

}
